<?php
namespace Modules\Code\Http\Controllers\Admin\V1;

use Illuminate\Http\Request;
use Illuminate\Routing\Controller;

use Modules\Code\Entities\Code;

use Validator;
use ThrowException;
use Auth;
use DB;

class CodeController extends Controller
{
    public function index(Request $req)
    {
        $rule = [
        ];
        Validator::make($req->all(), $rule)->fails() && ThrowException::BadRequest(); 

        $options = $req->all();

        // $options['order_by'] = ['list_weight' => 'desc'];
        $options['with'] = ['coupon', 'chip'];

        $list = Code::getList($options);

        return $list->generateListResponse();
    }

    public function store(Request $req)
    {
        $rule = [
            'code' => ['required'],
            'title' => ['required'],
            'stock' => ['required'],
            'code_type' => ['required']
        ];
        Validator::make($req->all(), $rule)->fails() && ThrowException::BadRequest(); 

        if (strlen($req->code) < 4 || strlen($req->code) > 19) {
            ThrowException::Conflict('兑换码请控制在4至19个字符之间');
        }

        $info = $req->all();

        $item = Code::create($info);

        return [
            'id' => $item->id,
            'uuid' => $item->uuid
        ];
    }

    public function batchCreate(Request $req)
    {
        $rule = [
            'code_rule' => ['required'],
            'code_total' => ['required'],
            'title' => ['required'],
            'stock' => ['required'],
            'code_type' => ['required'],
            'batch_number' => ['required']
        ];
        Validator::make($req->all(), $rule)->fails() && ThrowException::BadRequest(); 

        $codeRule = $req->code_rule;
        $codeTotal = $req->code_total;

        if (strpos($codeRule, '{A}') === false && strpos($codeRule, '{0}') === false) {
            ThrowException::Conflict('兑换码规则需包含{A}或{0}');
        }

        $codeList = Code::get();

        $newCodeList = [];


        for ($i=0; $i < $codeTotal; $i++) { 
            $temp = $codeRule;

            // 替换字母
            while (($index = strpos($temp, '{A}')) !== false) {
                $temp = substr_replace($temp, chr(rand(65,90)), $index, 3);
            }

            // 替换数字
            while (($index = strpos($temp, '{0}')) !== false) {
                // $temp = substr_replace('{0}', rand(0,9), $temp);
                $temp = substr_replace($temp, rand(0,9), $index, 3);
            }

            if ($codeList->where('code', $temp)->first() || in_array($temp, $newCodeList)) {
                $i --;
                continue;
            }

            array_push($newCodeList, $temp);
        }

        $info = $req->all();
        unset($info['code_rule']);
        unset($info['code_total']);
        $info['created_at'] = now();

        $newCodeList = array_map(function ($item) use ($info) {
            $info['uuid'] = uniqid();
            $info['code'] = $item;
            return $info;
        }, $newCodeList);


        collect($newCodeList)->chunk(2000)->each(function ($list, $key) {
            // \Log::error($list);
            DB::table('codes')->insert($list->all());
        });
        // DB::table('codes')->insert($newCodeList);

        return [];
    }

    public function show(Request $req, $uuid)
    {
        $rule = [
        ];
        Validator::make($req->all(), $rule)->fails() && ThrowException::BadRequest(); 

        $item = Code::getEntity([
            'uuid' => $uuid
        ]);

        $info = $item->getInfo();

        return [
            'info' => $info
        ];
    }

    public function update(Request $req, $uuid)
    {
        $rule = [
        ];
        Validator::make($req->all(), $rule)->fails() && ThrowException::BadRequest(); 

        $item = Code::getEntity([
            'uuid' => $uuid
        ]);

        if ($req->type === 'update') {
            $info = $req->input('attributes');
            $item->update($info);
        }

        return [];
    }

    public function destroy(Request $req, $uuid)
    {
        $rule = [
        ];
        Validator::make($req->all(), $rule)->fails() && ThrowException::BadRequest(); 

        $item = Code::getEntity([
            'uuid' => $uuid
        ]);

        $item->delete();

        return [];
    }
}
